<template>
  <view>
    <a-tree-select v-model:value="deptId" show-search style="width: 100%"
      :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" allow-clear tree-default-expand-all :tree-data="treeData"
      :field-names="{ children: 'children', label: 'name', value: 'id' }" tree-node-filter-prop="name"
      @change="selectNode()">
    </a-tree-select>
  </view>
</template>
<script setup>
import { queryOne, queryTree } from '@/module/system/api/dept'
import { queryList } from '@/module/system/api/user'
import emitter from '@/utils/mitt'
const emit = defineEmits(['search', 'confirm'])
const props = defineProps({
  deptId: {
    type: String
  }
})
const projectDept = ref();
const deptId = ref(undefined);
const treeData = ref([])
const deptData = ref([])
const userData = ref([])
const query = ref({ pageNum: 1, pageSize: 10, sortBy: 'id', searchKey: '', deptId: '' });

watch(() => props.deptId, (newValue) => {
  console.log('props.deptId', props.deptId);
  deptId.value = props.deptId
  // selectBuckle.value = newValue;
});

// 获取Tree
function buildTeamTree() {
  Promise.all([
    queryTree(),// 部门树
    queryList(query.value), // 用户列表
  ]).then(res => {
    console.log(res);
    deptData.value = res[0][0].children
    userData.value = res[1].content

    // 合并部门树和用户列表
    // let merged = mergeDepartmentsAndUsers(deptData.value, userData.value);
    // let mergedTree = JSON.stringify(merged, null, 2)
    // treeData.value = JSON.parse(mergedTree);
    // console.log(treeData.value);
  })
}
buildTeamTree();

// 合并部门树和用户列表
function mergeDepartmentsAndUsers(departments, users) {
  // 将用户按照部门ID分组
  let usersByDeptId = {};
  users.forEach(user => {
    if (!usersByDeptId[user.deptId]) {
      usersByDeptId[user.deptId] = [];
    }
    usersByDeptId[user.deptId].push(user);
  });
  // 遍历部门树，为每个部门添加children属性
  departments.forEach(dept => {
    if (usersByDeptId[dept.id]) {
      dept.children = usersByDeptId[dept.id];
    } else {
      dept.children = [];
    }
    // 如果部门有子部门，递归调用mergeDepartmentsAndUsers
    if (dept.children.length > 0) {
      // 添加终止条件，避免无限递归
      if (dept.children.every(child => !usersByDeptId[child.id])) {
        mergeDepartmentsAndUsers(dept.children, users);
      }
    }
  });
  return departments;
}

function selectNode() {
  // console.log('deptId.value', deptId.value);
  if (deptId.value) {
    queryOne(deptId.value).then(resFir => {
      projectDept.value = resFir.deptName
      // console.log(resFir);
      emit('confirm', projectDept.value)
    })
  }
}

</script>